package org.example;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.google.gson.Gson;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
//        final ExecutorService executor = Executors.newFixedThreadPool(8);

        final Properties prop = new Properties();
        final String filePath = Class.forName("org.example.Main").getClassLoader().getResource("prop.properties").getPath();
        prop.load(new FileInputStream(filePath));
        final String urlStr = prop.getProperty("get_url");
        final String username = prop.getProperty("Username");
        final String ticket = prop.getProperty("Access-ticket");
//        System.out.println(prop);
        System.out.println("urlStr = " + urlStr);
        System.out.println("username = " + username);
        System.out.println("ticket = " + ticket);
        final HttpRequest httpRequest = HttpRequest.get(urlStr);
        httpRequest.header("Accept", "application/json");
        httpRequest.header("Username", username);
        httpRequest.header("Access-ticket", ticket);
        final HttpResponse response = httpRequest.execute();
        final int status = response.getStatus();
        System.out.println("status = " + status);
        final String body = response.body();
//        System.out.println(body);
        final Gson gson = new Gson();
        final VO vo = gson.fromJson(body, VO.class);

        final List<Row> rows = vo.getRows();
//        Executors.
        final List<String> programIdErrorList = new ArrayList<>();
        final List<String> programIdWaitList = new ArrayList<>();
        final StringBuilder builder = new StringBuilder("select  count(*),sync_status  from data_sync_task where program_id in (");
        final StringBuilder builder2 = new StringBuilder("select  count(*) from data_sync_task where program_id in (");
        System.out.println("rows.size() = " + rows.size());
        final List<String> nulList = new ArrayList<>();
        int count = 0;
        int other = 0;
        int nul = 0;
        for (int i = 0; i < rows.size(); i++) {
            final Row row = rows.get(i);
            final String syncStatus = row.getSyncStatus();

            if (syncStatus == null) {
                nulList.add(row.getItemId()+"");
                nul++;
                continue;
            }else {
                switch (syncStatus){
                    case "success":
                        count++;
                        continue;
                    case "wait_callback":
                        programIdWaitList.add(row.getItemId() + "");
                        continue;
                    case "error_xml":
                        programIdErrorList.add(row.getItemId()+"");
                        break;
                    default:
                        other++;
                }
            }
            if (null==syncStatus){

            }else {
                if (!"error_xml".equals(syncStatus) && !"error".equals(syncStatus)) {
                    continue;
                }
            }
            final Long itemId = row.getItemId();
            final Long appId = row.getAppId();
            final String recodeUrl = prop.getProperty("recode_url");
            final String reAdi_url = prop.getProperty("reAdi_url");
//            executor.submit(() -> extracted(row, itemId, appId, prop, recodeUrl, reAdi_url));
            extracted(row, itemId, appId, prop, recodeUrl, reAdi_url);
        }
//        executor.shutdown();
        final String wait = programIdWaitList.stream().map(s -> "'" + s + "'").collect(Collectors.joining(","));
        final String error = programIdErrorList.stream().map(s -> "'" + s + "'").collect(Collectors.joining(","));
        builder.append(wait).append(") group by sync_status\\G;");
        builder2.append(error).append(")\\G;");
        System.out.println("查询等待状态的sql：");
        System.out.println(builder);
        System.out.println("查询错误状态的sql：");
        System.out.println(builder2);
        final int waitCount = programIdWaitList.size();
        final int errorCount = programIdErrorList.size();
        System.out.println("等待条数："+waitCount);
        System.out.println("错误条数："+errorCount);
        System.out.println("成功条数："+count);
        System.out.println("其他状态条数："+other);
        System.out.println("空状态："+nul);
        System.out.println("total="+(waitCount+errorCount+count+other+nul));
    }

    private static void extracted(Row row, Long itemId, Long appId, Properties prop, String recodeUrl, String reAdi_url) {
        final long start = System.currentTimeMillis();
        System.out.println(Thread.currentThread().getName()+":"+"row.getItemName() = " + row.getItemName());
//        process(itemId, appId, prop, recodeUrl, "转码");
        final long transEnd = System.currentTimeMillis();
        System.out.println(Thread.currentThread().getName()+":"+"本次转码耗时"+(start-transEnd)+"ms");
        process(itemId, appId, prop, reAdi_url, "注入");
        final long adiEnd = System.currentTimeMillis();
        System.out.println(Thread.currentThread().getName()+":"+"本次注入耗时"+(adiEnd-transEnd)+"ms");
    }

    public static void process(Long itemId, Long appId, Properties prop, String recodeUrl, String message) {
        System.out.println(Thread.currentThread().getName()+":"+"正在" + message + " 处理中:itemId=" + itemId);
        final HttpRequest httpRequest = HttpRequest.post(recodeUrl);
        final String username = prop.getProperty("Username");
        final String ticket = prop.getProperty("Access-ticket");
        httpRequest.header("Accept", "application/json");
        httpRequest.header("Username", username);
        httpRequest.header("Access-ticket", ticket);
        httpRequest.body(new RequestBody(appId, itemId).toString());
//        httpRequest.body("{\n" +
//                "    \"itemId\": "+itemId+"\n" +
//                "}");
        final HttpResponse response = httpRequest.execute();
        final String body = response.body();
        System.out.println(Thread.currentThread().getName()+":"+message + "完成:" + body);
    }


}